package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.MapUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.pojo.response.CardInfo;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Pattern;


/*
*  美团单车
* */
@Slf4j
public class Plugin_ECARD_P034 implements ChannelService {


    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {
       try {
           //资格校验
           String accountVal = String.valueOf(data.get("AccountVal"));
           HashMap<String, String> submitParams = new HashMap<>();

           if(Pattern.matches("^1[3456789]\\d{9}$", accountVal) == true){
               submitParams.put("mobileNo",accountVal);
           }else {
               submitParams.put("mtUserId",accountVal);
           }
           String apiSource = apiConfig.getString("ApiSource");
           submitParams.put("performanceSource",apiSource);
           submitParams.put("activityId",String.valueOf(data.get("SUPProductId")));
           String key = apiConfig.getString("SecretKey");
           String sign = sign(submitParams, key);
           submitParams.put("sign",sign);
           String verifyUrl = apiConfig.getString("VerifyUrl");
           String respStr = HttpTool.HttpPost(verifyUrl, submitParams);
           log.info("美团单车鉴权接口返回"+respStr);
           JSONObject respObj = JSONObject.parseObject(respStr);
           String code = respObj.getString("code");
           String message = respObj.getString("message");
           if (code.equals("2012")) {
                return ChannelResult.error(message);
           }
           if (!code.equals("0")) {
                return ChannelResult.FAILED(message);
           }

           submitParams.remove("sign");
           submitParams.put("channelTransToken",String.valueOf(data.get("ChannelOrderCode")));
           String subSign = sign(submitParams, key);
           submitParams.put("sign",subSign);
           String submitUrl = apiConfig.getString("SubmitUrl");
           String respSStr = HttpTool.HttpPost(submitUrl, submitParams);
           log.info("美团单车下单接口返回"+respSStr);
           JSONObject parseObject = JSONObject.parseObject(respSStr);
           String subCode = parseObject.getString("code");
           String subMessage = parseObject.getString("message");
           if (subCode.equals("0")) {
               return ChannelResult.success("充值成功");
           }
           if (subCode.equals("2101")){
            return ChannelResult.IN_PROCESS("充值成功");//重复订单 - 状态为成功
           }
           if (subCode.equals("2102")) {
            return ChannelResult.error(subMessage);
           }
          return ChannelResult.FAILED(subMessage);
       }catch (Exception e) {
           e.printStackTrace();
           log.error("美团单车提交订单接口错误：",e);
           return  ChannelResult.error("美团单车提交订单接口错误");
       }
    }

        /*  mtUserId Long 美团⽤户ID ⼆选⼀
            mobileNo String ⽤户⼿机号

            performanceSource 履约来源
            channelTransToken 交易凭证 订单id
            activityId   活动ID
            requestSource 请求来源
            sign
         */

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

     /*  1007⽆效渠道
            1009 权益卡ID⾮法
            2001 注册⽤户失败
            2003 没有获取到⽤户信息*/
        try {

            HashMap<String, String> queryParams = new HashMap<>();
            String accountVal = String.valueOf(data.get("AccountVal"));
            if(Pattern.matches("^1[3456789]\\d{9}$", accountVal) == true){
                queryParams.put("mobileNo",accountVal);
            }else {
                queryParams.put("mtUserId",accountVal);
            }
            String apiSource = apiConfig.getString("ApiSource");
            queryParams.put("performanceSource",apiSource);
            queryParams.put("channelTransToken",String.valueOf(data.get("ChannelOrderCode")));
            queryParams.put("activityId",String.valueOf(data.get("SUPProductId")));
            String key = apiConfig.getString("SecretKey");
            String sign = sign(queryParams, key);
            queryParams.put("sign",sign);
            queryParams.put("requestSource","1");

            String queryUrl = apiConfig.getString("QueryUrl");
            String respStr = HttpTool.HttpPost(queryUrl, queryParams);
            JSONObject respObj = JSONObject.parseObject(respStr);
            String code = respObj.getString("code");
            String message = respObj.getString("message");
            if (code.equals("0")){
                return ChannelResult.success("充值成功");
            }
            if (code.equals("2202")){
                return ChannelResult.error(message);
            }
        return ChannelResult.FAILED(message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("美团单车查询订单接口错误：",e);
            return  ChannelResult.error("美团单车查询订单接口错误");
        }
    }

    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return ChannelResult.success("success");
    }

    public static String sign(Map<String, String> params, String key) throws
            UnsupportedEncodingException {
        if (MapUtils.isEmpty(params) || StringUtils.isBlank(key)) {
            return StringUtils.EMPTY;
        }
        TreeMap<String, String> fields = new TreeMap<>();
        for (Map.Entry<String, String> en : params.entrySet()) {
            if ("sign".equals(en.getKey())) {
                continue;
            }
            fields.put(en.getKey(), en.getValue());
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : fields.entrySet()) {
            if (StringUtils.isBlank(entry.getValue()) ||
                    "null".equals(entry.getValue())) {
                continue;
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String before = sb.append(key).toString();
        String after = DigestUtils.md5Hex(before.getBytes("utf8")).toUpperCase();
        log.debug("md5 sign before : {}, after : {}", before, after);
        return after;

    }

}
